/**
 * 轮播图管理API路由
 * 支持轮播图的增删改查操作
 */

import { Router } from 'express'
import multer from 'multer'
import path from 'path'
import fs from 'fs'
import { authenticateToken } from '../middleware/auth'

const router = Router()

// 配置文件上传
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    const uploadPath = path.join(process.cwd(), 'uploads', 'banners')
    if (!fs.existsSync(uploadPath)) {
      fs.mkdirSync(uploadPath, { recursive: true })
    }
    cb(null, uploadPath)
  },
  filename: (req, file, cb) => {
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9)
    cb(null, 'banner-' + uniqueSuffix + path.extname(file.originalname))
  }
})

const upload = multer({ 
  storage,
  fileFilter: (req, file, cb) => {
    // 只允许图片文件
    if (file.mimetype.startsWith('image/')) {
      cb(null, true)
    } else {
      cb(new Error('只允许上传图片文件') as any)
    }
  },
  limits: {
    fileSize: 5 * 1024 * 1024 // 5MB
  }
})

// 轮播图数据接口
interface BannerItem {
  id: number
  title: string
  description?: string
  imageUrl: string
  linkUrl?: string
  linkType: 'internal' | 'external' | 'none'
  isActive: boolean
  sortOrder: number
  startTime?: Date
  endTime?: Date
  createdAt: Date
  updatedAt: Date
}

// 内存存储轮播图数据（生产环境建议使用数据库）
let banners: BannerItem[] = [
  {
    id: 1,
    title: '医疗数字孪生系统',
    description: '智能化医疗管理平台',
    imageUrl: '/static/images/biao.png',
    linkUrl: '/pages/services/index',
    linkType: 'internal',
    isActive: true,
    sortOrder: 1,
    createdAt: new Date(),
    updatedAt: new Date()
  },
  {
    id: 2,
    title: '在线问诊服务',
    description: '24小时在线医生咨询',
    imageUrl: '/static/images/liao.jpeg', 
    linkUrl: '/pages/consultation/index',
    linkType: 'internal',
    isActive: true,
    sortOrder: 2,
    createdAt: new Date(),
    updatedAt: new Date()
  },
  {
    id: 3,
    title: '健康体检预约',
    description: '便民体检服务预约',
    imageUrl: '/static/images/yi.jpg',
    linkUrl: '/pages/appointment/index',
    linkType: 'internal', 
    isActive: true,
    sortOrder: 3,
    createdAt: new Date(),
    updatedAt: new Date()
  }
]

// 获取轮播图列表（公开接口，供小程序使用）
router.get('/list', (req, res) => {
  try {
    const { active = 'true' } = req.query
    
    let filteredBanners = banners.filter(banner => {
      // 过滤激活状态
      if (active === 'true' && !banner.isActive) {
        return false
      }
      
      // 过滤时间范围
      const now = new Date()
      if (banner.startTime && now < banner.startTime) {
        return false
      }
      if (banner.endTime && now > banner.endTime) {
        return false
      }
      
      return true
    })
    
    // 按排序字段排序
    filteredBanners = filteredBanners.sort((a, b) => a.sortOrder - b.sortOrder)
    
    res.json({
      success: true,
      data: filteredBanners,
      total: filteredBanners.length
    })
  } catch (error) {
    console.error('获取轮播图列表失败:', error)
    res.status(500).json({
      success: false,
      message: '获取轮播图列表失败',
      error: error instanceof Error ? error.message : String(error)
    })
  }
})

// 获取轮播图管理列表（需要管理员权限）
router.get('/admin/list', authenticateToken, (req, res) => {
  try {
    const { page = 1, pageSize = 10 } = req.query
    const pageNum = parseInt(page as string)
    const size = parseInt(pageSize as string)
    
    // 分页
    const start = (pageNum - 1) * size
    const end = start + size
    const paginatedBanners = banners.slice(start, end)
    
    res.json({
      success: true,
      data: paginatedBanners,
      total: banners.length,
      page: pageNum,
      pageSize: size,
      totalPages: Math.ceil(banners.length / size)
    })
  } catch (error) {
    console.error('获取轮播图管理列表失败:', error)
    res.status(500).json({
      success: false,
      message: '获取轮播图管理列表失败',
      error: error instanceof Error ? error.message : String(error)
    })
  }
})

// 获取单个轮播图详情
router.get('/:id', (req, res) => {
  try {
    const id = parseInt(req.params.id)
    const banner = banners.find(b => b.id === id)
    
    if (!banner) {
      return res.status(404).json({
        success: false,
        message: '轮播图不存在'
      })
    }
    
    res.json({
      success: true,
      data: banner
    })
  } catch (error) {
    console.error('获取轮播图详情失败:', error)
    res.status(500).json({
      success: false,
      message: '获取轮播图详情失败',
      error: error instanceof Error ? error.message : String(error)
    })
  }
})

// 创建轮播图（需要管理员权限）
router.post('/admin/create', authenticateToken, upload.single('image'), (req, res) => {
  try {
    const {
      title,
      description,
      linkUrl,
      linkType = 'internal',
      isActive = true,
      sortOrder,
      startTime,
      endTime
    } = req.body
    
    if (!title) {
      return res.status(400).json({
        success: false,
        message: '标题不能为空'
      })
    }
    
    if (!req.file) {
      return res.status(400).json({
        success: false,
        message: '请上传轮播图片'
      })
    }
    
    const newBanner: BannerItem = {
      id: Math.max(...banners.map(b => b.id), 0) + 1,
      title,
      description,
      imageUrl: `/uploads/banners/${req.file.filename}`,
      linkUrl,
      linkType,
      isActive: isActive === 'true' || isActive === true,
      sortOrder: sortOrder ? parseInt(sortOrder) : banners.length + 1,
      startTime: startTime ? new Date(startTime) : undefined,
      endTime: endTime ? new Date(endTime) : undefined,
      createdAt: new Date(),
      updatedAt: new Date()
    }
    
    banners.push(newBanner)
    
    res.json({
      success: true,
      message: '轮播图创建成功',
      data: newBanner
    })
  } catch (error) {
    console.error('创建轮播图失败:', error)
    res.status(500).json({
      success: false,
      message: '创建轮播图失败',
      error: error instanceof Error ? error.message : String(error)
    })
  }
})

// 更新轮播图（需要管理员权限）
router.put('/admin/:id', authenticateToken, upload.single('image'), (req, res) => {
  try {
    const id = parseInt(req.params.id)
    const bannerIndex = banners.findIndex(b => b.id === id)
    
    if (bannerIndex === -1) {
      return res.status(404).json({
        success: false,
        message: '轮播图不存在'
      })
    }
    
    const {
      title,
      description,
      linkUrl,
      linkType,
      isActive,
      sortOrder,
      startTime,
      endTime
    } = req.body
    
    const existingBanner = banners[bannerIndex]
    
    // 如果上传了新图片，删除旧图片
    if (req.file && existingBanner.imageUrl && existingBanner.imageUrl.startsWith('/uploads/')) {
      const oldImagePath = path.join(process.cwd(), existingBanner.imageUrl)
      if (fs.existsSync(oldImagePath)) {
        fs.unlinkSync(oldImagePath)
      }
    }
    
    // 更新轮播图数据
    banners[bannerIndex] = {
      ...existingBanner,
      title: title || existingBanner.title,
      description: description !== undefined ? description : existingBanner.description,
      imageUrl: req.file ? `/uploads/banners/${req.file.filename}` : existingBanner.imageUrl,
      linkUrl: linkUrl !== undefined ? linkUrl : existingBanner.linkUrl,
      linkType: linkType || existingBanner.linkType,
      isActive: isActive !== undefined ? (isActive === 'true' || isActive === true) : existingBanner.isActive,
      sortOrder: sortOrder ? parseInt(sortOrder) : existingBanner.sortOrder,
      startTime: startTime ? new Date(startTime) : existingBanner.startTime,
      endTime: endTime ? new Date(endTime) : existingBanner.endTime,
      updatedAt: new Date()
    }
    
    res.json({
      success: true,
      message: '轮播图更新成功',
      data: banners[bannerIndex]
    })
  } catch (error) {
    console.error('更新轮播图失败:', error)
    res.status(500).json({
      success: false,
      message: '更新轮播图失败',
      error: error instanceof Error ? error.message : String(error)
    })
  }
})

// 删除轮播图（需要管理员权限）
router.delete('/admin/:id', authenticateToken, (req, res) => {
  try {
    const id = parseInt(req.params.id)
    const bannerIndex = banners.findIndex(b => b.id === id)
    
    if (bannerIndex === -1) {
      return res.status(404).json({
        success: false,
        message: '轮播图不存在'
      })
    }
    
    const banner = banners[bannerIndex]
    
    // 删除图片文件
    if (banner.imageUrl && banner.imageUrl.startsWith('/uploads/')) {
      const imagePath = path.join(process.cwd(), banner.imageUrl)
      if (fs.existsSync(imagePath)) {
        fs.unlinkSync(imagePath)
      }
    }
    
    // 从数组中删除
    banners.splice(bannerIndex, 1)
    
    res.json({
      success: true,
      message: '轮播图删除成功'
    })
  } catch (error) {
    console.error('删除轮播图失败:', error)
    res.status(500).json({
      success: false,
      message: '删除轮播图失败',
      error: error instanceof Error ? error.message : String(error)
    })
  }
})

// 批量更新轮播图排序（需要管理员权限）
router.put('/admin/batch/sort', authenticateToken, (req, res) => {
  try {
    const { bannerIds } = req.body
    
    if (!Array.isArray(bannerIds)) {
      return res.status(400).json({
        success: false,
        message: '参数格式错误'
      })
    }
    
    // 更新排序
    bannerIds.forEach((id, index) => {
      const bannerIndex = banners.findIndex(b => b.id === id)
      if (bannerIndex !== -1) {
        banners[bannerIndex].sortOrder = index + 1
        banners[bannerIndex].updatedAt = new Date()
      }
    })
    
    res.json({
      success: true,
      message: '排序更新成功'
    })
  } catch (error) {
    console.error('更新排序失败:', error)
    res.status(500).json({
      success: false,
      message: '更新排序失败',
      error: error instanceof Error ? error.message : String(error)
    })
  }
})

// 批量更新轮播图状态（需要管理员权限）
router.put('/admin/batch/status', authenticateToken, (req, res) => {
  try {
    const { bannerIds, isActive } = req.body
    
    if (!Array.isArray(bannerIds) || typeof isActive !== 'boolean') {
      return res.status(400).json({
        success: false,
        message: '参数格式错误'
      })
    }
    
    // 更新状态
    bannerIds.forEach(id => {
      const bannerIndex = banners.findIndex(b => b.id === id)
      if (bannerIndex !== -1) {
        banners[bannerIndex].isActive = isActive
        banners[bannerIndex].updatedAt = new Date()
      }
    })
    
    res.json({
      success: true,
      message: '状态更新成功'
    })
  } catch (error) {
    console.error('更新状态失败:', error)
    res.status(500).json({
      success: false,
      message: '更新状态失败',
      error: error instanceof Error ? error.message : String(error)
    })
  }
})

export default router